package com.baichen.eventloop;

public class ScheduleTask implements Runnable, Comparable<ScheduleTask> {

    private final Runnable task;

    private long deadline;

    private final long period;

    private final EventLoop eventLoop;

    public ScheduleTask(Runnable task, long deadline, long period, EventLoop eventLoop) {
        this.task = task;
        this.deadline = deadline;
        this.period = period;
        this.eventLoop = eventLoop;
    }

    @Override
    public int compareTo(ScheduleTask o) {
        return Long.compare(deadline, o.deadline);
    }

    public long getDeadline() {
        return deadline;
    }

    @Override
    public void run() {
        try {
            task.run();
        } finally {
            if (period > 0) {
                deadline += period;
                eventLoop.getScheduleTaskQueue().add(this);
            }
        }
    }
}
